'''
    @project: Masdevallia
    @author: Austin Baker
    @created: 2/22/2014
    @license: http://opensource.org/licenses/mit-license.php

    The MIT License (MIT)

    Copyright (c) 2014 Austin Baker
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
    ------
    
    About: Utility functions for working with QT windows.
'''

'''
============================================================
--->>   IMPORT MODULES
============================================================
'''
import os

import maya.OpenMayaUI as OMUI

from shiboken import wrapInstance
from PySide import QtCore
from PySide import QtGui
import pysideuic
import xml.etree.ElementTree as XML
from cStringIO import StringIO


'''
============================================================
--->>   UTILITY METHODS
============================================================
'''
def mayaMainWindow():
    '''
    Return the Maya main window widget as a Python object
    
    @return: Maya Main Window.
    '''
    main_window_ptr = OMUI.MQtUtil.mainWindow()
    return wrapInstance( long( main_window_ptr ), QtGui.QWidget )

def clearLayout( layout ):
    '''
    Clears all the sub-objects from the sub_layout.
    
    @param layout: QLayout.
    '''
    if layout is not None:
        while layout.count():
            item = layout.takeAt( 0 )
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                clearLayout( item.layout() )
                
def mayaToQtObject( inMayaUI ):
    '''
    Converts a Maya UI object to a QT object.
    
    @param inMayaUI: Maya UI Object.
    @return: QT Object.
    '''
    ptr = OMUI.MQtUtil.findControl( inMayaUI )
    if ptr is None:
        ptr = OMUI.MQtUtil.findLayout( inMayaUI )
    if ptr is None:
        ptr= OMUI.MQtUtil.findMenuItem( inMayaUI )
    if ptr is not None:
        return wrapInstance( long( ptr ), QtGui.QWidget )
    
def loadUiType( inUiFile ):
    '''
    Convert a QT Designer UI file to Python code in memory. Then execute it in a
    frame to get the form class.
    
    @param inUiFile: QT Designer UI file.
    @return: QT base class and QT form class for the QT Designer UI file.
    '''
    parsedUi = XML.parse( inUiFile )
    widgetClass = parsedUi.find( 'widget' ).get( 'class' )
    formClass = parsedUi.find( 'class' ).text
    
    # Open the UI file.
    with open( inUiFile, 'r' ) as f:
        o = StringIO()
        frame = {}
        
        pysideuic.compileUi( f, o, indent=0 )
        pyc = compile( o.getvalue(), '<string>', 'exec' )
        exec pyc in frame
        
        # Get the base class and form class based on their type.
        formClass = frame[ 'Ui_{0}'.format( formClass ) ]
        baseClass = eval( 'QtGui.{0}'.format( widgetClass ) )
        
    return formClass, baseClass